package com.example.ccj.u.map;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.CoordinateConverter;
import com.amap.api.maps2d.model.LatLng;
import com.example.ccj.b.a.OneMarkerLocation;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.PermissionUtils;
import com.example.ccj.u.PermissonUtils;
import com.example.ccj.u.ToastUtils;

import java.util.List;


/**
 * 经纬度转换,经纬度工具
 */
public class LocationUtil {
    static double PI = 3.1415926535897932384626;
    static double a = 6378245.0;
    static double ee = 0.00669342162296594323;


    /**
     * 获取一次位置
     * @param context 上下文
     * @throws Exception 异常
     */
    public static void getOneLocation(Context context,LocationListener locationListener) throws Exception {
        AMapLocationClient.updatePrivacyShow(context,true,true);
        AMapLocationClient.updatePrivacyAgree(context,true);
        AMapLocationClient locationClientSingle = new AMapLocationClient(context);
        //设置为高精度定位模式s

        //单次客户端的定位监听
        locationClientSingle.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation.getErrorCode() == 0) locationListener.onResult(new LocationMode(aMapLocation.getLongitude(),aMapLocation.getLatitude()));
                else {
//                    locationListener.onError("获取定位失败，请重试！" + aMapLocation.getErrorInfo() + aMapLocation.getErrorCode());
                    LogUtils.e("获取定位失败，请重试！" + aMapLocation.getErrorInfo() + aMapLocation.getErrorCode());
//                    ToastUtils.showShort("获取定位失败，请重试！" + aMapLocation.getErrorInfo() + aMapLocation.getErrorCode());
                    locationListener.onError("获取定位失败，请重试！");
                }
            }
        });
        //获取一次定位结果：
        //该方法默认为false。
        AMapLocationClientOption locationClientSingleOption = new AMapLocationClientOption();
        locationClientSingleOption.setOnceLocation(true);
        //高精度定位
        locationClientSingleOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //关闭缓存机制
        locationClientSingleOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        locationClientSingle.setLocationOption(locationClientSingleOption);
        //启动定位
        locationClientSingle.startLocation();
    }

    private static int errorCount = 0;

    /**
     * 获取连续定位
     * @param context 上下文
     * @param locationListener 定位返回监听
     * @param interval 每次获取间隔（毫秒）
     * @throws Exception 异常
     */
    public static void getContinueLocation (Context context,long interval, LocationListener locationListener) throws Exception {
        AMapLocationClient.updatePrivacyShow(context,true,true);
        AMapLocationClient.updatePrivacyAgree(context,true);
        AMapLocationClient locationClientContinue = new AMapLocationClient(context);
        //连续客户端的定位监听
        locationClientContinue.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                LogUtils.d("获取到" + aMapLocation.getErrorCode() + aMapLocation.getErrorInfo());
                if (aMapLocation.getErrorCode() == 0) {
                    locationListener.onResult(new LocationMode(aMapLocation.getLongitude(),aMapLocation.getLatitude()));
                    errorCount = 0;
                } else {
                    errorCount ++;
                    if (errorCount > 3) {
                        locationListener.onError("获取定位连续失败多次，请重试！");
                        LogUtils.e("获取定位连续失败多次，请重试！");
                        locationClientContinue.stopLocation();
                        errorCount = 0;
                    }
                }
            }
        });
        AMapLocationClientOption locationClientContinueOption = new AMapLocationClientOption();
        //高精度定位
        locationClientContinueOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        if (interval <= 0) interval = 1000;
        locationClientContinueOption.setInterval(interval);
        //给定位客户端对象设置定位参数
        locationClientContinue.setLocationOption(locationClientContinueOption);
        //启动定位
        locationClientContinue.startLocation();
    }


    /**
     * GPS转百度
     * @param longitude
     * @param latitude
     * @return
     */
    public static double[] gpsToBaiDu(double longitude, double latitude){
        double[] point = wgs2bd(latitude, longitude);
        return point;
    }

    /**
     * 百度坐标系转高德
     * @param bd_lat
     * @param bd_lon
     * @return
     */
    public static double[] baiDuToGaoDe(double bd_lon,double bd_lat) {
        double[] gd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gd_lat_lon[0] = z * Math.cos(theta);
        gd_lat_lon[1] = z * Math.sin(theta);
        return gd_lat_lon;
    }

    /**
     * 高德坐标系转百度
     * @param gd_lon
     * @param gd_lat
     * @return
     */
    public static double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }

    /**
     * GPS转高德
     * @return
     */
    public static LatLng gpsToGaoDe(Context context, double longitude, double latitude){
        LatLng latlng1 = new LatLng(latitude,longitude);
        CoordinateConverter converter  = new CoordinateConverter();
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标点
        converter.coord(latlng1);
        // 执行转换操作
        return converter.convert();
    }

    /**
     * 高德转GPS
     * @param longitude
     * @param latitude
     * @return
     */
    public static double[] gaoDeToGps(double longitude,double latitude){
        return gcj02towgs84(longitude,latitude);
    }

    /**
     * GCJ02 转换为 WGS84
     * @param lng
     * @param lat
     * @returns {*[]}
     */
    public static double[] gcj02towgs84(double lng, double lat){
        double dlat = transformlat(lng - 105.0, lat - 35.0);
        double dlng = transformlng(lng - 105.0, lat - 35.0);
        double radlat = lat / 180.0 * PI;
        double magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        double sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
        double mglat = lat + dlat;
        double mglng = lng + dlng;
        return new double[] { lng * 2 - mglng, lat * 2 - mglat };
    }

    private static double transformlng(double lng,double lat){ double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
    }

    private static double transformlat(double lng,double lat){ double ret= -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    public static double[] wgs2bd(double lat, double lon) {
        double[] wgs2gcj = wgs2gcj(lat, lon);
        double[] gcj2bd = gcj2bd(wgs2gcj[0], wgs2gcj[1]);
        return gcj2bd;
    }

    static double pi = 3.14159265358979324;
    public final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    public static double[] gcj2bd(double lat, double lon) {
        double x = lon, y = lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double bd_lon = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        return new double[] { bd_lat, bd_lon };
    }
    public static double[] wgs2gcj(double lat, double lon) {
        double dLat = transformLat(lon - 105.0, lat - 35.0);
        double dLon = transformLon(lon - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * pi;
        double magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
        double mgLat = lat + dLat;
        double mgLon = lon + dLon;
        double[] loc = { mgLat, mgLon };
        return loc;
    }

    private static double transformLat(double lat, double lon) {
        double ret = -100.0 + 2.0 * lat + 3.0 * lon + 0.2 * lon * lon + 0.1 * lat * lon + 0.2 * Math.sqrt(Math.abs(lat));
        ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lon * pi) + 40.0 * Math.sin(lon / 3.0 * pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lon / 12.0 * pi) + 320 * Math.sin(lon * pi  / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    private static double transformLon(double lat, double lon) {
        double ret = 300.0 + lat + 2.0 * lon + 0.1 * lat * lat + 0.1 * lat * lon + 0.1 * Math.sqrt(Math.abs(lat));
        ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lat / 12.0 * pi) + 300.0 * Math.sin(lat / 30.0 * pi)) * 2.0 / 3.0;
        return ret;
    }
}

